#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from common.core.make_response import (
    make_error, make_validation_error, make_server_error
)
from common.core.exceptions import (
    BizException, AuthException, ForbiddenException, NotFoundException
)

def init_error_handlers(app: Flask):
    @app.errorhandler(BizException)
    def handle_biz_error(e):
        return make_error(msg=e.msg, code=e.code, data=e.data)

    @app.errorhandler(AuthException)
    def handle_auth_error(e):
        return make_error(msg=e.msg, code=e.code)

    @app.errorhandler(ForbiddenException)
    def handle_forbidden(e):
        return make_error(msg=e.msg, code=e.code)

    @app.errorhandler(NotFoundException)
    def handle_not_found(e):
        return make_error(msg=e.msg, code=e.code)

    @app.errorhandler(422)
    def handle_validation_error(e):
        # Flask-WTF 或 marshmallow 校验失败
        errors = getattr(e, "data", {}).get("messages", {})
        return make_validation_error(errors)

    @app.errorhandler(Exception)
    def handle_global_exception(e):
        # 未捕获的异常
        # 你也可以加 loguru 打日志
        print(f"系统异常: {e}")
        return make_server_error()